package com.cgycms.webdeploy.storage;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.cgycms.webdeploy.ftp.FtpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @ClassName : ServersPool
 * @Description : 服务器容器信息
 * @Author : 王力超
 * @Date: 2020-11-04 16:56
 */
@Configuration
public class ServersPool {

    private static Logger log = LoggerFactory.getLogger(ServersPool.class);

    /**
     * 服务容器
     */
    private static Map<String, ArrayList<FtpUtil>> SERVERS;

    /**
     * 服务分组
     */
    private static Map<String, Object> SERVER_GROUP;

    /**
     * 服务标签
     */
    private static Map<String, Object> SERVER_TITLE;

    /**
     * 服务数量
     */
    private static Integer serverCount = 0;

    @Autowired
    private ServersLoad serversLoad;


    @PostConstruct
    public void init() {
        loadServer(true);
    }

    /**
     * 创建容器
     */
    private void createServerContext() {
        //全部退出
        if (!CollectionUtil.isEmpty(SERVERS)) {
            SERVERS.forEach((k, v) -> {
                v.parallelStream().forEach(a -> {
                    a.quit();
                });
            });
        }
        SERVERS = new ConcurrentHashMap<>(2);
        SERVER_GROUP = new ConcurrentHashMap<>(2);
        SERVER_TITLE = new ConcurrentHashMap<>(2);
        serverCount = 0;
    }

    /**
     * 加载服务器配置信息
     *
     * @param ref 是否重读配置文件
     * @return
     */
    public boolean loadServer(boolean ref) {

        createServerContext();

        List<Servers> servers = serversLoad.get(ref);
        if (CollectionUtil.isEmpty(servers)) {
            log.error("服务器信息未配置!程序无法失败!");
            System.exit(0);
        }

        serverCount = servers.size();

        servers.parallelStream().forEach(server -> {

            if (StrUtil.isBlank(server.getGroup())) {
                log.error("服务信息分组不能为空！[{}]", server.getHost());
                System.exit(0);
            }

            SERVER_GROUP.put(server.getGroup(), server.getGroup());
            if (StrUtil.isNotBlank(server.getTitle())) {
                SERVER_TITLE.put(server.getTitle(), server.getTitle());
            }

            FtpUtil connect = new FtpUtil(
                    server.getHost(),
                    server.getPort(),
                    server.getUsername(),
                    server.getPassword(),
                    "/",
                    "/",
                    server.getGroup(),
                    server.getTitle())
                    .createConnect();

            if (SERVERS.containsKey(server.getGroup())) {
                SERVERS.get(server.getGroup()).add(connect);
            } else {
                ArrayList ftps = new ArrayList<>();
                ftps.add(connect);
                SERVERS.put(server.getGroup(), ftps);
            }
        });
        return true;
    }


    /**
     * 获取服务信息
     *
     * @param host  ip
     * @param title 标签
     * @param env   分组
     * @param all   是否获取全部
     * @return
     */
    public static List<FtpUtil> getServersWheres(String host, String env, String title, boolean all) {
        List<FtpUtil> servers = new ArrayList<>();
        //为空并获取全部
        if (StrUtil.isBlank(host) && StrUtil.isBlank(env) && StrUtil.isBlank(title) && all == false) {
            return servers;
        }
        if (StrUtil.isBlank(env) && StrUtil.isBlank(title) && all == true) {
            servers = ServersPool.getServerAll();
            return servers;
        }
        if (StrUtil.isNotBlank(host)) {
            servers = ServersPool.getServerByHost(host);
        }
        if (StrUtil.isNotBlank(title)) {
            servers = ServersPool.getServerByTitle(title);
        }
        if (StrUtil.isNotBlank(env)) {
            servers = ServersPool.getServerByGroup(env);
        }
        return servers;
    }

    /**
     * 根据分组获取服务信息
     *
     * @param group 分组名称
     * @return
     */
    private static List<FtpUtil> getServerByGroup(String group) {
        return SERVERS.get(group);
    }


    /**
     * 根据title获取服务信息
     *
     * @param title 标签名称
     * @return
     */
    private static List<FtpUtil> getServerByTitle(String title) {
        List<FtpUtil> serverAll = getServerAll();
        List<FtpUtil> result = serverAll.stream().filter(s -> title.equals(s.getTitle())).collect(Collectors.toList());
        return result;
    }

    /**
     * 根据ip获取服务信息
     *
     * @param host ip
     * @return
     */
    private static List<FtpUtil> getServerByHost(String host) {
        List<FtpUtil> serverAll = getServerAll();
        List<FtpUtil> result = serverAll.stream().filter(s -> host.equals(s.getHost())).collect(Collectors.toList());
        return result;
    }

    /**
     * 获取所有服务
     *
     * @return
     */
    private static List<FtpUtil> getServerAll() {
        List<FtpUtil> result = new ArrayList<>(2);
        SERVERS.forEach((k, v) -> {
            result.addAll(v);
        });
        return result;
    }

    /**
     * 获取分组数量
     *
     * @return
     */
    public static int getServerGroupNumber() {
        return SERVERS.size();
    }

    /**
     * 服务器数量
     *
     * @return
     */
    public static int getServerNumber() {
        return serverCount;
    }


    public static Map<String, Object> getServerAllTitle() {
        return SERVER_TITLE;
    }

    public static Map<String, Object> getServerGroup() {
        return SERVER_GROUP;
    }

}
